package com.mogujie.tt.ui.adapter;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.TextAppearanceSpan;
import android.view.ContextThemeWrapper;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.mogujie.tt.DB.sp.LoginSp;
import com.mogujie.tt.DB.sp.RegisterSp;
import com.mogujie.tt.R;
import com.mogujie.tt.ui.helper.Emoparser;
import com.mogujie.tt.ui.widget.QuanzDynamicImageGridView;
import com.mogujie.tt.ui.widget.QuanzQzMessageDetail;
import com.mogujie.tt.ui.widget.QuanzQzPhone;
import com.mogujie.tt.ui.widget.QuanzQzReply;
import com.mogujie.tt.ui.widget.QuanzQzReplyListView;
import com.mogujie.tt.utils.GETUtil;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import net.tsz.afinal.FinalBitmap;

import org.json.JSONArray;
import org.json.JSONObject;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 50281 on 2015/9/15.
 */
public class QuanzDynamicAdapter extends BaseAdapter implements OnClickListener{

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private Context context;
    private List<QuanzQzMessageDetail> list;
    private QuanzQzMessageDetail messageDetail;
    private PopupWindow replayWindow;
    private PopupWindow editWindow;
    private FlushListView flush;
    private PopupWindow mpopupWindow;
    private EditText replyEdit;
    private View emo_layout_publish;
    private TextView sendBtn;
    private ImageView reply_emo_btn;
    private int kkk;
    private DisplayImageOptions options;
    private FinalBitmap finalBit;
    private Map<String,String> map;
    private String o_edit ="";

    ImageButton discuss ;
    ImageButton favuor;
    ImageButton favuorCancle;
    private QuanzQzReply quanzQzReply;// 临时引用
    private QuanzQzReplyAdapter quanzQzReplyAdapter;
    private View curView = null;
    private String o_feed_id;
    private String o_uid;
    private String vo_feed_id;
    private String o_f_feed_id;
    private String o_sendName;
    private String o_replyName;

    public QuanzDynamicAdapter(Context context, PopupWindow window, PopupWindow editwindow, final FlushListView flush){

        this.context = context;
        this.replayWindow = window;
        this.editWindow = editwindow;
        this.flush = flush;
        map=new HashMap<String,String>();
        finalBit = FinalBitmap.create(context);
    }

    @Override
    public int getCount() {
        return list == null ? 0 : list.size();
    }

    @Override
    public Object getItem(int i) {
        return list == null ? null : list.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }
    public void setData(List<QuanzQzMessageDetail> list) {
        this.list = list;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(
                    R.layout.quanz_qz_item, null);
            holder = getHolder(convertView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        if (list != null) {
            messageDetail = list.get(position);
            messageDetail.position = position;
            convertView.setId(messageDetail.id);
            bindData(holder);
        }
        kkk=position;
        DisplayImageOptions options = new DisplayImageOptions.Builder()//
                .showImageOnLoading(R.drawable.ic_launcher) // 加载中显示的默认图片
                .showImageOnFail(R.drawable.ic_launcher) // 设置加载失败的默认图片
                .cacheInMemory(true)//
                .cacheOnDisk(true)//
                .bitmapConfig(Bitmap.Config.RGB_565)//
                .build();
        ImageLoader.getInstance().displayImage(messageDetail.photo,holder.photo,options);
        return convertView;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.reply_icon:// 显示评论窗口
                messageDetail = (QuanzQzMessageDetail)v.getTag();
                vo_feed_id = String.valueOf(messageDetail.friendId);
                showDialog(v);
                break;
            case R.id.discuss:
                replyEdit = (EditText) editWindow.getContentView().findViewById(
                        R.id.reply);
                replyEdit.setOnClickListener(this);
                sendBtn = (TextView) editWindow.getContentView().findViewById(
                        R.id.send_reply);
                emo_layout_publish = editWindow.getContentView().findViewById(R.id.emo_layout_publish);
                emo_layout_publish.setVisibility(View.GONE);
                reply_emo_btn = (ImageView) editWindow.getContentView().findViewById(R.id.reply_emo_btn);
                reply_emo_btn.setOnClickListener(this);
                reply_emo_btn.setTag(v.getTag());
                sendBtn.setOnClickListener(this);
                sendBtn.setTag(v.getTag());
                showDiscussDialog("0", "0","0","0");
                flush.showDiscussDialog(messageDetail.position);
                break;
            case R.id.favuor:
                messageDetail = (QuanzQzMessageDetail)v.getTag();
                new AsyncTask<String, Void, Object>() {
                    protected void onPostExecute(Object result) {
                        super.onPostExecute(result);
                        try {
                            JSONObject status = new JSONObject(result.toString());
                            if (status.getString("status").equals("1")){
                                favuor.setVisibility(View.GONE);
                                favuorCancle.setVisibility(View.VISIBLE);
                                if (!messageDetail.favourName.equals("")){
                                    messageDetail.favourName= RegisterSp.instance().getSpDetailedInfo().getDetailedNickName()+"、"+messageDetail.favourName;
                                }else {
                                    messageDetail.favourName= RegisterSp.instance().getSpDetailedInfo().getDetailedNickName();
                                }
                                //flush.showFavour();
                                messageDetail.favour="qwe";
                                flush.addTrendParise(String.valueOf(messageDetail.id));
                            }else if (status.getString("status").equals("0")){

                            }
                        } catch (Exception e) {
                            System.out.println("1111111Qz  " + e.getMessage());
                        }
                    }
                    protected Object doInBackground(String... params) {
                        String result = GETUtil.instance().sendGet(GETUtil.instance().getRequestText("public", "Index", "addDigg",
                                LoginSp.instance().getLoginIdentity().getLoginName(), LoginSp.instance().getLoginIdentity().getPwd(), messageDetail.friendId+"",null,null,null,null,null,null));
                        return result;
                    }
                }.execute();
                break;
            case R.id.favuor_cancle:
                messageDetail = (QuanzQzMessageDetail)v.getTag();
                new AsyncTask<String, Void, Object>() {
                    protected void onPostExecute(Object result) {
                        super.onPostExecute(result);
                        try {
                            favuorCancle.setVisibility(View.GONE);
                            favuor.setVisibility(View.VISIBLE);
                            JSONObject status = new JSONObject(result.toString());
                            if (status.getString("status").equals("1")){
                                String[] favour=messageDetail.favourName.split("、");
                                if (favour.length>1){
                                    String fav="";
                                    if (fav!=""){
                                        for (int i=2;i<favour.length;i++){
                                            fav=fav+"、"+favour[i];
                                        }
                                    }else {
                                        fav=" "+favour[1];
                                    }
                                    messageDetail.favourName=fav;
                                }else{
                                    messageDetail.favourName="";
                                }
                                messageDetail.favour="";
                                flush.delTrendById(String.valueOf(messageDetail.id));
                            }else if (status.getString("status").equals("0")){

                            }
                        } catch (Exception e) {
                            System.out.println("1111111Qz  " + e.getMessage());
                        }
                    }
                    protected Object doInBackground(String... params) {
                        String result = GETUtil.instance().sendGet(GETUtil.instance().getRequestText("public", "Index", "delDigg",
                                LoginSp.instance().getLoginIdentity().getLoginName(), LoginSp.instance().getLoginIdentity().getPwd(), messageDetail.friendId+"",null,null,null,null,null,null));
                        return result;
                    }
                }.execute();
                break;
            case R.id.send_reply:
                emo_layout_publish.setVisibility(View.GONE);
                messageDetail = (QuanzQzMessageDetail)v.getTag();
                if (o_uid.equals("0")||o_feed_id.equals("0")){
                    o_edit = replyEdit.getText().toString();
                    o_replyName = "";
                }else {
                    o_edit = "回复@"+o_sendName+"："+replyEdit.getText().toString();
                    vo_feed_id = o_f_feed_id;
                    o_replyName = o_sendName;
                }
                if (TextUtils.isEmpty(replyEdit.getText().toString())){
                    Toast.makeText(context,"请输入。。。",Toast.LENGTH_SHORT).show();
                    return;
                }
                new AsyncTask<String, Void, Object>() {
                    protected void onPostExecute(Object result) {
                        super.onPostExecute(result);
                        try {
                            JSONObject status = new JSONObject(result.toString());
                            if (status.getString("status").equals("1")){
                                JSONObject data = status.getJSONObject("data");
                                JSONObject result1 = data.getJSONObject("result");
                                JSONObject user_info = result1.getJSONObject("user_info");
                                QuanzQzReply reply  = new QuanzQzReply();
                                reply.content = replyEdit.getText().toString();
                                reply.replyName = o_replyName;
                                reply.userId = user_info.getString("uid");
                                reply.friendId = Integer.valueOf(result1.getString("comment_id"));//就是在回复数据库中的id  ***
                                reply.id = Integer.valueOf(result1.getString("row_id"));
                                reply.sendName = user_info.getString("nick");
                                reply.f_friendId = Integer.valueOf(o_f_feed_id);
                                if (o_uid.equals("0")||o_feed_id.equals("0")){
                                    messageDetail.replyList.add(0,reply);
                                }else {

                                }
                                flush.flush();
                                replyEdit.setText("");
                                editWindow.dismiss();
                            }else if (status.getString("status").equals("0")){
                                Toast.makeText(context,"评论失败",Toast.LENGTH_SHORT).show();
                            }
                        } catch (Exception e) {
                            System.out.println("1111111Qz  " + e.getMessage());
                        }
                    }
                    protected Object doInBackground(String... params) {

                        String result = null;
                        try {
                            result = GETUtil.instance().sendGet(GETUtil.instance().getRequestText1("public", "Index", "addcomment",
                                    LoginSp.instance().getLoginIdentity().getLoginName(), LoginSp.instance().getLoginIdentity().getPwd(), "public", "feed",
                                    String.valueOf(LoginSp.instance().getLoginIdentity().getLoginId()),vo_feed_id, o_feed_id, o_uid, URLEncoder.encode(o_edit, "GBK")));
                            return result;
                        } catch (Exception e) {
                            System.out.println("1111111Qz  " + e.getMessage());
                        }
                     return "";
                    }
                }.execute();
                break;
            case R.id.delete:
                messageDetail = (QuanzQzMessageDetail)v.getTag();
                if (LoginSp.instance().getLoginIdentity().getLoginId()!=Integer.valueOf(messageDetail.userId)){
                    Toast.makeText(context,"您没有删除该分享的权限",Toast.LENGTH_SHORT).show();
                    return;
                }
                AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(context, android.R.style.Theme_Holo_Light_Dialog));
                LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                View dialog_view = inflater.inflate(R.layout.tt_custom_dialog, null);
                final EditText editText = (EditText)dialog_view.findViewById(R.id.dialog_edit_content);
                editText.setVisibility(View.GONE);
                TextView textText = (TextView)dialog_view.findViewById(R.id.dialog_title);
                textText.setText("确认删除？");
                builder.setView(dialog_view);
                builder.setPositiveButton(context.getString(R.string.tt_ok), new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        new AsyncTask<String, Void, Object>() {
                            protected void onPostExecute(Object result) {
                                super.onPostExecute(result);
                                try {
                                    JSONObject status = new JSONObject(result.toString());
                                    if ("1".equals(status.getString("status"))) {
                                        list.remove(messageDetail.position);
                                        flush.showDel(list.size());
                                        notifyDataSetChanged();
                                        Toast.makeText(context, "删除成功", Toast.LENGTH_SHORT);
                                    } else {
                                        Toast.makeText(context, "删除失败，" + status.getString("msg"), Toast.LENGTH_SHORT);
                                    }
                                } catch (Exception e) {
                                    System.out.println("1111111Qz  " + e.getMessage());
                                }
                            }

                            protected Object doInBackground(String... params) {
                                String result = GETUtil.instance().sendGet(GETUtil.instance().getRequestText("public", "Index", "removeFeed",
                                        LoginSp.instance().getLoginIdentity().getLoginName(), LoginSp.instance().getLoginIdentity().getPwd(), String.valueOf(messageDetail.friendId), null, null, null, null, null, null));
                                return result;
                            }
                        }.execute();
                        dialog.dismiss();
                    }
                });
                builder.setNegativeButton(context.getString(R.string.tt_cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                });
                builder.show();
                break;
            case R.id.reply_emo_btn:
                flush.handReply(v);
                break;
            case R.id.reply:
                emo_layout_publish.setVisibility(View.GONE);
                break;
        }
    }

    private void showDiscussDialog(final String to_feed_id,final String to_uid,String f_feed_id,String sendName) {
        o_feed_id=to_feed_id;
        o_uid=to_uid;
        o_f_feed_id = f_feed_id;
        o_sendName = sendName;
    }


    private List<QuanzQzReply> replys;// 临时引用
    private void bindData(final ViewHolder holder) {

        if (messageDetail == null)
            return;
        holder.name.setText(messageDetail.name);
        if (messageDetail.contentText.isEmpty()) {
            holder.contentText.setVisibility(View.GONE);
        } else {
            holder.contentText.setVisibility(View.VISIBLE);
        }
        holder.contentText.setText(Emoparser.getInstance(context).emoCharsequence(messageDetail.contentText));
        if (messageDetail.linkUrl.isEmpty()) {
            holder.linkContent.setVisibility(View.GONE);
        } else {
            holder.linkContent.setVisibility(View.GONE);
            holder.linkIcon.setImageResource(R.drawable.tt_logo2);
            holder.linkDescription.setText("我只是做个测试");
        }
        holder.sendDate.setText(handTime(messageDetail.sendDate));

        if (LoginSp.instance().getLoginIdentity().getLoginId()!=Integer.valueOf(messageDetail.userId)){
            holder.delText.setVisibility(View.GONE);
        }else {
            holder.delText.setVisibility(View.VISIBLE);
        }
        // 判断是否有点赞
        if (messageDetail.favourName.isEmpty()) {
            holder.favourTemp.setVisibility(View.GONE);
        } else {
            holder.favourTemp.setVisibility(View.VISIBLE);
            if (listIsEmpty(messageDetail.replyList)) {// 只有点赞 则不显示分隔线
                holder.praiseLine.setVisibility(View.GONE);
            } else {
                holder.praiseLine.setVisibility(View.GONE);
            }
        }
        String[] favour=messageDetail.favourName.split("、");
        String fav="";
        String fav1="";
        if (favour.length>5){
            if (fav!=""){
                for (int i=1;i<5;i++){
                    fav=fav+"、"+favour[i];
                }
                fav1="等"+favour.length+"人觉的很赞";
            }else {
                fav=" "+favour[0];
            }
        }else{
            fav=messageDetail.favourName;
            fav1="觉得很赞";
        }

        SpannableString styledText = new SpannableString(fav+fav1);
        styledText.setSpan(new TextAppearanceSpan(context, R.style.style0), 0, fav.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        styledText.setSpan(new TextAppearanceSpan(context, R.style.style1), fav.length(),fav.length()+ fav1.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        holder.favourName.setText(styledText,TextView.BufferType.SPANNABLE);
        // 判断点赞 与回复是否都没有内容
        if (messageDetail.favourName.isEmpty() && listIsEmpty(messageDetail.replyList)) {
            holder.replyContent.setVisibility(View.GONE);
        } else {
            holder.replyContent.setVisibility(View.VISIBLE);
        }

        // 判断是否有回复内容
        if (listIsEmpty(messageDetail.replyList)) {
            holder.replyList.setVisibility(View.GONE);
        } else {
            holder.replyList.setVisibility(View.VISIBLE);
        }


        // 分享类型
        holder.shareType.setVisibility(View.GONE);

        // 判断是否有发表图片
        if (messageDetail.images.isEmpty()) {
            holder.images.setVisibility(View.GONE);
        } else {
            holder.images.setVisibility(View.VISIBLE);
            final ArrayList<QuanzQzPhone> list = getPhotos(messageDetail.images);
            if (list != null) {
                holder.images.setAdapter(new QuanzQzImageAdapter(context, list, false));
                holder.images.setOnItemClickListener(new OnItemClickListener() {  // 设置监听器 ，点击进入大图
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    }
                });
            }
        }
        quanzQzReplyAdapter = new QuanzQzReplyAdapter(context,messageDetail.position,editWindow,new Quanzflush());
        replys = messageDetail.replyList;
        // =========判断是否有更多回复=========
        checkMoreReply(holder);
        // ==============================

        // ==================评论==================
        quanzQzReplyAdapter.setData(replys);
        holder.replyList.setAdapter(quanzQzReplyAdapter);
        holder.replyList.setTag(replys);
        holder.replyList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view,
                                           final int position, long id) {

                replys = (List<QuanzQzReply>) parent.getTag();
                if (LoginSp.instance().getLoginIdentity().getLoginId()==Integer.valueOf(replys.get(position).userId)){
                    popupWindowShow(parent,position,holder);
                }else {
                    Toast.makeText(context,"您没有删除该评论的权限",Toast.LENGTH_SHORT).show();
                }
                return false;
            }
        });
        // ==================评论end==================
        holder.delText.setTag(messageDetail);
        holder.delText.setOnClickListener(this);
//		flush.showDel(holder.delText, friend.userId);
        holder.replyIcon.setTag(messageDetail);
        holder.replyIcon.setOnClickListener(this);
    }


    /**
     * 处理时间
     *
     * @param time
     * @return
     */
    private String handTime(String time) {
        if (time == null || "".equals(time.trim())) {
            return "";
        }
        try {
            Date date = format.parse(time);
            long tm = System.currentTimeMillis();// 当前时间戳
            long tm2 = date.getTime();// 发表动态的时间戳
            long d = (tm - tm2) / 1000;// 时间差距 单位秒
            if ((d / (60 * 60 * 24)) > 0) {
                return d / (60 * 60 * 24) + "天前";
            } else if ((d / (60 * 60)) > 0) {
                return d / (60 * 60) + "小时前";
            } else if ((d / 60) > 0) {
                return d / 60 + "分钟前";
            } else {
                // return d + "秒前";
                return "刚刚";
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            System.out.println("1111111Qz  " + e.getMessage());
        }
        return null;
    }

    /**
     * 判断集合是否是需要的格式 （不为null size>0）
     *
     * @param list
     * @return
     */
    private boolean listIsEmpty(List list) {
        if (list != null && list.size() > 0)
            return false;
        return true;

    }



    /**
     * 处理图片数据
     *
     * @param photo
     * @return
     */
    private ArrayList<QuanzQzPhone> getPhotos(String photo) {
        if (!photo.contains("[")) {
            return null;
        }
        ArrayList<QuanzQzPhone> phs = new ArrayList<QuanzQzPhone>();
        try {
            JSONArray array = new JSONArray(photo);
            int size = array.length();
            JSONObject obj;
            QuanzQzPhone ph;
            for (int i = 0; i < size; i++) {
                obj = array.getJSONObject(i);
                ph = new QuanzQzPhone();
                ph.min = obj.getString("attach_small");
                ph.max = obj.getString("attach_url");
                phs.add(ph);
            }
            return phs;
        } catch (Exception e) {
            System.out.println("1111111Qz  " + e.getMessage());
        }
        return null;
    }

    /**
     * 显示评论弹窗
     *
     * @param view
     */
    private void showDialog(View view) {
        int width = view.getWidth();
        messageDetail = (QuanzQzMessageDetail) view.getTag();
        int[] location = new int[2];
        view.getLocationInWindow(location);
        int x = location[0] - dip2px(context, width) - width - 140;
        int y = location[1] - 20;
        View v = replayWindow.getContentView();
        discuss = (ImageButton) v.findViewById(R.id.discuss);
        favuor = (ImageButton) v.findViewById(R.id.favuor);
        favuorCancle = (ImageButton) v.findViewById(R.id.favuor_cancle);

        favuorCancle.setOnClickListener(this);
        discuss.setOnClickListener(this);
        favuor.setOnClickListener(this);
        discuss.setTag(view.getTag());
        favuor.setTag(view.getTag());
        favuorCancle.setTag(view.getTag());
        replayWindow.showAtLocation(view, Gravity.NO_GRAVITY, x, y);
        if (messageDetail.favour==null || messageDetail.favour.equals("")){
            favuorCancle.setVisibility(View.GONE);
            favuor.setVisibility(View.VISIBLE);
        }else {
            favuorCancle.setVisibility(View.VISIBLE);
            favuor.setVisibility(View.GONE);
        }

    }


    public int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    public int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }
    /**
     * 初始化ViewHolder
     *
     * @param convertView
     * @return
     */
    private ViewHolder getHolder(View convertView) {
        ViewHolder holder = new ViewHolder();
        holder.shareType = (TextView) convertView.findViewById(R.id.share_type);
        holder.photo = (ImageView) convertView.findViewById(R.id.photo);
        holder.name = (TextView) convertView.findViewById(R.id.name);
        holder.contentText = (TextView) convertView
                .findViewById(R.id.content_text);
        holder.linkIcon = (ImageView) convertView.findViewById(R.id.link_icon);
        holder.linkDescription = (TextView) convertView
                .findViewById(R.id.link_description);
        holder.sendDate = (TextView) convertView.findViewById(R.id.date);
        holder.delText = (TextView) convertView.findViewById(R.id.delete);
        holder.replyIcon = (ImageButton) convertView
                .findViewById(R.id.reply_icon);
        holder.favourName = (TextView) convertView
                .findViewById(R.id.favuor_name);
        holder.replyList = (QuanzQzReplyListView) convertView
                .findViewById(R.id.reply_list);
        holder.linkContent = (LinearLayout) convertView
                .findViewById(R.id.link_content);
        holder.replyContent = (LinearLayout) convertView
                .findViewById(R.id.reply_content);
        holder.favourTemp = (LinearLayout) convertView
                .findViewById(R.id.favour_temp);
        holder.replyMore = (TextView) convertView.findViewById(R.id.reply_more);
        holder.images = (QuanzDynamicImageGridView) convertView
                .findViewById(R.id.image_content);
        holder.praiseLine = convertView.findViewById(R.id.praise_line);
        return holder;
    }



    private class ViewHolder {
        public TextView shareType;// 分享类型
        public ImageView photo;// 头像
        public TextView name;// 名字
        public TextView contentText;// 文字内容
        public ImageView linkIcon;// 链接图标
        public TextView linkDescription;// 链接描述
        public TextView sendDate;// 发表时间
        public TextView delText;// 删除文字
        public ImageButton replyIcon;// 回复icon
        public TextView favourName;// 点赞的名字
        public QuanzQzReplyListView replyList;// 回复的listView
        public LinearLayout linkContent;// 链接内容
        public LinearLayout replyContent;// 回复布局
        public LinearLayout favourTemp;// 点赞布局
        public TextView replyMore;// 更多回复
        public QuanzDynamicImageGridView images;// 发表的图片 最多8张

        public View praiseLine;// 点赞下面的线
    }


    /**
     * 回调接口 实现数据刷新
     *
     * @author jiangyue
     *
     */
    public interface FlushListView {
        public void flush();// 刷新数据

        public void showDiscussDialog(int position);// 显示评论对话框

        public void getReplyByTrendId(Object tag);// 根据动态id获取评论回复

        public void showFavour();

        public void getViewPosition(int position);

        public void delParise(String valueOf);// 删除点赞

        public void showCancle(QuanzQzMessageDetail friend);// 显示或者隐藏赞

        public void saveReply(QuanzQzReply reply);// 保存回复信息

        public void addTrendParise(String trendId);// 添加点赞

        public void delTrendById(String trendId);// 根据id删除动态

        public void showDel(int size);// 显示删除按钮

        public void handReply(View view);// 处理评论

    }

    /**
     * 显示评论窗
     *
     * //@param type
     * @param v
     */
//    @Deprecated
    private void showDiscuss(View v) {
        messageDetail = (QuanzQzMessageDetail) v.getTag();
        final int id = messageDetail.id;
        // getViewPosition(friend.position);// 获取view的位置
        replyEdit.setFocusable(true);
        replyEdit.requestFocus();
        // 设置焦点，不然无法弹出输入法
        editWindow.setFocusable(true);
        // 以下两句不能颠倒
        editWindow.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
        editWindow
                .setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        int[] location = new int[2];
        v.getLocationInWindow(location);
        editWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
       // editWindow.showAtLocation(, Gravity.BOTTOM, 0, 0);
        // 显示键盘
        final InputMethodManager manager = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        manager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
        editWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                manager.toggleSoftInput(0, InputMethodManager.RESULT_SHOWN);
            }
        });
        sendBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                quanzQzReply = new QuanzQzReply();
                // reply.sendName =userInfo.getUsername();
                quanzQzReply.content = replyEdit.getEditableText().toString();
                quanzQzReply.friendId = id;
                // db.save(reply);
                flush.saveReply(quanzQzReply);
                // flush.flush();
                editWindow.dismiss();
                replyEdit.setText("");
            }
        });

        replayWindow.dismiss();
    }


    private void checkMoreReply(ViewHolder holder) {
        int replyCount = messageDetail.replyCount;
        if (replyCount > 10 && replyCount != messageDetail.replyList.size()) {// 最多显示10条
            holder.replyMore.setVisibility(View.VISIBLE);
            holder.replyMore.setTag(messageDetail.friendId);
            holder.replyMore.setOnClickListener(this);
        } else {
            holder.replyMore.setVisibility(View.GONE);
        }
    }
    public class Quanzflush implements QuanzQzReplyAdapter.FlushListView1 {

        @Override
        public void flush(int pos,String to_feed_id,String to_uid,String f_feed_id,String sendName,View v) {
            showDiscussDialog(to_feed_id, to_uid,f_feed_id,sendName);
            flush.showDiscussDialog(pos);
        }

        @Override
        public void flushmesshage(View v) {
            flush.handReply(v);
            quanzQzReplyAdapter.notifyDataSetChanged();
        }

        @Override
        public void flushdetails() {

        }

    }

    private void popupWindowShow(final AdapterView<?> parent,final int position,ViewHolder holder){

        replys = (List<QuanzQzReply>) parent.getTag();
        View view1 = View.inflate(context, R.layout.share_popup_menu, null);
        RelativeLayout rl_weixin = (RelativeLayout) view1.findViewById(R.id.rl_weixin);
        RelativeLayout rl_weibo = (RelativeLayout) view1.findViewById(R.id.rl_weibo);
        rl_weibo.setVisibility(View.GONE);
        Button bt_cancle = (Button) view1.findViewById(R.id.bt_cancle);
        TextView rl_tt = (TextView) view1.findViewById(R.id.rl_tt);
        rl_tt.setText("删除评论");
        TextView tv_weixin = (TextView) view1.findViewById(R.id.tv_weixin);
        tv_weixin.setText("删除");
        rl_weixin.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(context, android.R.style.Theme_Holo_Light_Dialog));
                LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                View dialog_view = inflater.inflate(R.layout.tt_custom_dialog, null);
                final EditText editText = (EditText)dialog_view.findViewById(R.id.dialog_edit_content);
                editText.setVisibility(View.GONE);
                TextView textText = (TextView)dialog_view.findViewById(R.id.dialog_title);
                textText.setText("确认删除？");
                builder.setView(dialog_view);
                builder.setPositiveButton(context.getString(R.string.tt_ok), new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        new AsyncTask<String, Void, Object>() {
                            protected void onPostExecute(Object result) {
                                super.onPostExecute(result);
                                try {
                                    JSONObject status = new JSONObject(result.toString());
                                    if ("1".equals(status.getString("status"))){
                                        ToastShow("删除成功");
                                        replys.remove(position);
                                        notifyDataSetChanged();
                                    }else {
                                        ToastShow("删除失败");
                                    }
                                } catch (Exception e) {
                                    System.out.println("1111111Qz  " + e.getMessage());
                                }
                            }
                            protected Object doInBackground(String... params) {
                                String result = GETUtil.instance().sendGet(GETUtil.instance().getRequestText4("public", "Index", "delComment",
                                        LoginSp.instance().getLoginIdentity().getLoginName(), LoginSp.instance().getLoginIdentity().getPwd(), String.valueOf(replys.get(position).friendId)));
                                return result;
                            }
                        }.execute();


                        dialog.dismiss();
                    }
                });
                builder.setNegativeButton(context.getString(R.string.tt_cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                });
                builder.show();


                mpopupWindow.dismiss();
            }
        });
        bt_cancle.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                mpopupWindow.dismiss();
            }
        });

        view1.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mpopupWindow.dismiss();
            }
        });

        view1.startAnimation(AnimationUtils.loadAnimation(context, R.anim.fade_in));
        LinearLayout ll_popup = (LinearLayout) view1.findViewById(R.id.ll_popup);
        ll_popup.startAnimation(AnimationUtils.loadAnimation(context, R.anim.push_bottom_in));

        if(mpopupWindow==null){
            mpopupWindow = new PopupWindow(context);
            mpopupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
            mpopupWindow.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
            mpopupWindow.setBackgroundDrawable(new BitmapDrawable());
            mpopupWindow.setFocusable(true);
            mpopupWindow.setOutsideTouchable(true);
        }
        mpopupWindow.setContentView(view1);
        mpopupWindow.showAtLocation(holder.replyList, Gravity.BOTTOM, 0, 0);
        mpopupWindow.update();
    }
    private void ToastShow(String tt){
        Toast.makeText(context,tt,Toast.LENGTH_SHORT).show();
    }
}
